package com.frame.auth.security.service;

import com.frame.auth.mvc.dao.mapper.CloudSysUserMapper;
import com.frame.auth.mvc.dao.pojo.CloudSysUser;
import com.frame.auth.mvc.dao.pojo.CloudSysUserExample;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @auther zhangwj
 * @date 2021/3/11 上午9:46
 */
@Configuration
public class AuthUserDetailsService implements UserDetailsService {

    @Resource
    private CloudSysUserMapper cloudSysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(userName)) {
            throw new UsernameNotFoundException("用户标识为空");
        }
        CloudSysUserExample cloudSysUserExample = new CloudSysUserExample();
        CloudSysUserExample.Criteria userCriteria = cloudSysUserExample.createCriteria();
        userCriteria.andUserNameEqualTo(userName);
        List<CloudSysUser> cloudSysUserList = cloudSysUserMapper.selectByExample(cloudSysUserExample);
        if (null == cloudSysUserList || cloudSysUserList.isEmpty()) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (cloudSysUserList.size() > 1) {
            throw new UsernameNotFoundException("用户不唯一");
        }
        return cloudSysUserList.get(0);
    }
}
